//
//  Person.m
//  MyCloud
//
//  Created by Visitor on 8/4/13.
//  Copyright (c) 2013 visitor.zc@gmail.com. All rights reserved.
//

#import "Person.h"

@implementation Person
static Person *_sharedPerson;

+ (Person *)sharedPerson
{
    if(!_sharedPerson)
    {
        _sharedPerson = [[Person alloc] init];
    }
    return _sharedPerson;
}

- (NSMutableArray *)getPersonList
{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    
    
    __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) {
        
        // we're on iOS 6
        NSLog(@"on iOS 6 or later, trying to grant access permission");
        
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else { // we're on iOS 5 or older
        
        NSLog(@"on iOS 5 or older, it is OK");
        accessGranted = YES;
    }
    
    if (accessGranted) {
        
        NSLog(@"we got the access right");
    }

    NSMutableArray *personList = [[NSMutableArray alloc] init];
    
    // 得到所有用户的数据
    CFArrayRef allPeoples = ABAddressBookCopyArrayOfAllPeople(addressBook);
    for(int i = 0; i < CFArrayGetCount(allPeoples); i++)
    {
        // 得到用户数组中某个人
        ABRecordRef people = CFArrayGetValueAtIndex(allPeoples, i);
        
        // 读取firstname
        NSString *peopleFiestName = (NSString*)ABRecordCopyValue(people, kABPersonFirstNameProperty);
        if(peopleFiestName != nil)
        {
            NSLog(@"%@",peopleFiestName);
        }
        // 读取lastname
        NSString *peopleLastName = (NSString*)ABRecordCopyValue(people, kABPersonLastNameProperty);
        if(peopleLastName != nil)
        {
            NSLog(@"%@",peopleLastName);
        }
        NSString *peopleEmail = nil;
        ABRecordCopyValue(people, kABPersonEmailProperty);
        
        ABMultiValueRef tmpEmails = ABRecordCopyValue(people, kABPersonEmailProperty);
        
        for(NSInteger j = 0; ABMultiValueGetCount(tmpEmails); j++)
            
        {
            
            NSString* tmpEmailIndex = (NSString*)ABMultiValueCopyValueAtIndex(tmpEmails, j);
            
            NSLog(@"Emails%d:%@", j, tmpEmailIndex);
            peopleEmail = tmpEmailIndex;
            [tmpEmailIndex release];
            
        }
        
        CFRelease(tmpEmails);
        // 读取电话多值
        ABMultiValueRef peoplePhones = ABRecordCopyValue(people, kABPersonPhoneProperty);
        NSString *peoplePhoneLabel;
        NSString *peoplePhone;
        NSMutableArray *allPhone = [[NSMutableArray alloc] init];
        for (int k = 0; k<ABMultiValueGetCount(peoplePhones); k++)
        {
            //获取电话Label
            peoplePhoneLabel = (NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(peoplePhones, k));
            //获取該Label下的电话值
            peoplePhone = (NSString *)ABMultiValueCopyValueAtIndex(peoplePhones, k);
            peoplePhone = [peoplePhone stringByReplacingOccurrencesOfString:@"(" withString:@""];
            peoplePhone = [peoplePhone stringByReplacingOccurrencesOfString:@")" withString:@""];
            peoplePhone = [peoplePhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            peoplePhone = [peoplePhone stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSLog(@"peoplePhone = %@",peoplePhone);
            [allPhone addObject:peoplePhone];
        }
        PersonInfo *info = [[PersonInfo alloc] init];
//        info.personLastName = peopleLastName;
//        info.personFirstName = peopleFiestName;
//        info.personPhones = allPhone;
//        info.personEmail = peopleEmail;
        NSMutableDictionary *peopleDict=[[NSMutableDictionary alloc] init] ;
        if (peopleFiestName) {
            [peopleDict setObject:peopleFiestName forKey:@"firstname"];
            
        }
        if (peopleLastName) {
            [peopleDict setObject:peopleLastName forKey:@"lastname"];
        }
        if (allPhone) {
            [peopleDict setObject:allPhone forKey:@"allphone"];
        }
        if (peopleEmail) {
            [peopleDict setObject:peopleEmail forKey:@"email"];

        }

        [allPhone release];
        [personList addObject:peopleDict];
        [info release];
        [peopleDict release];
    }
    NSLog(@"%@",personList);
    CFRelease(allPeoples);
    CFRelease(addressBook);
    return personList;
}



-(void)createNewPersonWithAddressBook:(ABAddressBookRef)paramAddressBook andPerson:(PersonInfo *)personInfo;
{
    ABRecordRef anthonyRobbins = [self newPersonWithAddressBook:paramAddressBook andPersonInfo:personInfo];
    if (anthonyRobbins != NULL)
    {
        NSLog(@"Anthony Robbins' record is inserted into the Address Book."); CFRelease(anthonyRobbins);
    }
}

- (ABRecordRef)newPersonWithAddressBook:(ABAddressBookRef)paramAddressBook andPersonInfo:(PersonInfo *)personInfo
{
    ABRecordRef result = NULL;
    if (paramAddressBook == NULL)
    {
        NSLog(@"The address book is NULL.");
        return NULL;
    }
    
    if ([personInfo.personFirstName length] == 0 && [personInfo.personLastName length] == 0)
    {
        NSLog(@"First name and last name are both empty.");
        return NULL;
    }
    
    result = ABPersonCreate();
    if (result == NULL){
        NSLog(@"Failed to create a new person.");
        return NULL;
    }
    BOOL couldSetFirstName = NO;
    BOOL couldSetLastName = NO;
    CFErrorRef setFirstNameError = NULL;
    CFErrorRef setLastNameError = NULL;
    
    
    //couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty,(__bridge CFTypeRef)paramFirstName,&setFirstNameError);
    
//    BOOL couldSetPhone = NO;
//    NSString *str = @"123456";
//    CFErrorRef setPhoneError = NULL;
    
    couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty, (CFTypeRef)personInfo.personFirstName, &setFirstNameError);
    couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty, (CFTypeRef)personInfo.personLastName, &setLastNameError);
//    couldSetPhone = ABRecordSetValue(result, kABPersonPhoneProperty, (CFStringRef)str, &setPhoneError);
    
    
    CFErrorRef couldAddPersonError = NULL;
    BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook, result, &couldAddPersonError);
    if (couldAddPerson)
    {
        NSLog(@"Successfully added the person.");
    }
    else
    {
        NSLog(@"Failed to add the person.");
        CFRelease(result);
        result = NULL;
        return result;
    }
    if (ABAddressBookHasUnsavedChanges(paramAddressBook))
    {
        CFErrorRef couldSaveAddressBookError = NULL;
        BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
        if (couldSaveAddressBook)
        {
            NSLog(@"Successfully saved the address book.");
        }
        else
        {
            NSLog(@"Failed to save the address book.");
        }
    }
    return result;

}


@end
